package lemon.dog.util;

import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.*;
import lemon.dog.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Date;

@Slf4j
public class JwtUtil {
    private static final long EXPIRE = 24 * 60 * 60 * 1000 * 3;
    private static final String APP_SECRET = "lemonage";
    public static String getJwtToken(User user) {
        String jwt = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("lemon_blog")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("user", JSON.toJSONString(user))
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
        return jwt;
    }
    public static boolean checkToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            log.info("token过期");
            return false;
        }
        return true;
    }

    public static User getUserByToken(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        String user = "" ;
        Object obj = body.get("user");
        if (obj instanceof String) {
            user = (String) obj;
            return JSON.parseObject(user, User.class);
        }
        throw new RuntimeException("token解析错误");
    }

}
